package xin.alum.aim.rocketmq;

import org.apache.rocketmq.client.apis.*;
import org.apache.rocketmq.client.apis.producer.Producer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import xin.alum.aim.constant.AimConstant;
import xin.alum.aim.groups.SessionGroups;
import xin.alum.aim.groups.Sessions;


@ConditionalOnProperty(prefix = AimConstant.CLUSTER_PROPERTIES_PREFIX, name = AimConstant.CLUSTER_PROPERTIES_MODE, havingValue = "rocketmq")
public class RocketMQConfig {

    @Value("${rocketmq.proxy:127.0.0.1:8081}")
    public String proxy;
    @Value("${rocketmq.consumer.group:consumer-group}")
    public String consumerGroup;
    @Value("${rocketmq.topic:aim-topic}")
    public String topic;

    @Value("${rocketmq.accessKey:rocketmq2}")
    public String accessKey;
    @Value("${rocketmq.secretKey:12345678}")
    public String secretKey;

    public final static  String  TAG_KILL="kill";

    @Bean
    public ClientServiceProvider clientServiceProvider ()
    {
        return ClientServiceProvider.loadService();
    }

    @Bean
    public ClientConfiguration configuration()
    {
        SessionCredentialsProvider sessionCredentialsProvider = new StaticSessionCredentialsProvider(accessKey, secretKey);
        return ClientConfiguration.newBuilder().enableSsl(false).setEndpoints(proxy).setCredentialProvider(sessionCredentialsProvider).build();
    }

    @Bean
    public Producer producer(ClientServiceProvider provider,ClientConfiguration configuration) throws ClientException {
        return provider.newProducerBuilder().setClientConfiguration(configuration).setTopics(topic).build();
    }

    @Bean
    @Primary
    public RocketMqProducer rocketMqProducer(ClientServiceProvider provider,Producer producer) {
       return new RocketMqProducer(this,provider,producer);
    }

    @Bean
    @Primary
    public RocketMqConsumer rocketMqConsumer(ClientServiceProvider provider, ClientConfiguration configuration, Jackson2JsonRedisSerializer<Object> json, Sessions sessions, SessionGroups groups){
        return new RocketMqConsumer(this,provider,configuration,json,sessions,groups);
    }

    @Bean
    public RocketMQPusher rocketMQPusher(RocketMqProducer producer,Jackson2JsonRedisSerializer<Object> json){
        return new RocketMQPusher(producer,json);
    }
}
